package com.myhdg.school;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.myhdg.school.dialog.LoginDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.BitmapCallback;

import okhttp3.Call;

public class LoginActivity extends AppCompatActivity {
    EditText idEdit;
    EditText passwordEdit;
    EditText verificationEdit;
    String id;
    String password;
    String verification;
    Button buttonLogin;

    CheckBox autoLogin;

    ImageView verificationImage;

    TextView forgetPassword;

    SharedPreferences idAndPassword;//学号密码配置文件
    SharedPreferences.Editor editorIdAndPassword;
    SharedPreferences autoLoginC;//自动登陆配置文件
    SharedPreferences.Editor editorAutoLogin;

    long firstTime = 0;//第一次点击返回键的时间


    //验证码获取链接
    private String codeUrl = "http://61.139.105.138/CheckCode.aspx";
    //登录链接
    private String loginUrl = "http://61.139.105.138/default2.aspx";
    //登录input隐式参数   （应该网络获取，这里写死了,一般值不会变   getViewstate可以联网获取  但是有问题  你看下)
    private String viewstate = "dDwyODE2NTM0OTg7Oz5xwfyqX7AwPfxgTOgX+8Gxg6Trhw==";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initCode();//初始化验证码图片

        idEdit = findViewById(R.id.id);
        passwordEdit = findViewById(R.id.password);
        verificationEdit = findViewById(R.id.verificationEdit);
        buttonLogin = findViewById(R.id.login);
        autoLogin = findViewById(R.id.autoLogin);
        verificationImage = findViewById(R.id.verificationImage);
        forgetPassword = findViewById(R.id.forget);

        idAndPassword = getPreferences(MODE_PRIVATE);
        editorIdAndPassword = idAndPassword.edit();

        autoLoginC = getPreferences(MODE_PRIVATE);
        editorAutoLogin = autoLoginC.edit();


        idEdit.setText(idAndPassword.getString("Id", ""));
        passwordEdit.setText(idAndPassword.getString("Password", ""));
        buttonLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                id = idEdit.getText().toString();
                password = passwordEdit.getText().toString();
                verification = verificationEdit.getText().toString();
                if (id.equals("") || password.equals("") || verification.equals("")) {
                    Snackbar.make(LoginActivity.this.findViewById(android.R.id.content), "不规则输入，请确认后登录", Snackbar.LENGTH_SHORT).show();
                } else {
                    final LoginDialog loginDialog = new LoginDialog(LoginActivity.this, new LoginDialog.LoginListener() {
                        @Override
                        public void getLoginState(int state) {
                            if (state == LoginDialog.LOGIN_SUCCESS) {
                                editorIdAndPassword.putBoolean("Login", true);
                                editorIdAndPassword.putString("Id", id);
                                editorIdAndPassword.putString("Password", password);
                                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                startActivity(intent);
                                LoginActivity.this.finish();
                            } else {
                                editorIdAndPassword.putBoolean("Login", false);
                                if (state == LoginDialog.LOGIN_FAIL_ID) {
                                    Snackbar.make(LoginActivity.this.findViewById(android.R.id.content), "学号错误，请确认后登录", Snackbar.LENGTH_SHORT).show();
                                }
                                if (state == LoginDialog.LOGIN_FAIL_PASSWORD) {
                                    Snackbar.make(LoginActivity.this.findViewById(android.R.id.content), "密码错误，请确认后登录", Snackbar.LENGTH_SHORT).show();
                                }
                                if (state == LoginDialog.LOGIN_FAIL_VERIFICATION) {
                                    Snackbar.make(LoginActivity.this.findViewById(android.R.id.content), "验证码错误，请确认后登录", Snackbar.LENGTH_SHORT).show();
                                }
                                if (state == LoginDialog.LOGIN_FAIL_INTERNET) {
                                    Snackbar.make(LoginActivity.this.findViewById(android.R.id.content), "网络错误，请确认网络连接后登录", Snackbar.LENGTH_SHORT).show();
                                }
                                if (state == LoginDialog.LOGIN_FAIL_OTHER) {
                                    Snackbar.make(LoginActivity.this.findViewById(android.R.id.content), "其他错误，请确认信息或重试", Snackbar.LENGTH_SHORT).show();
                                }
                            }
                            editorIdAndPassword.apply();//同步配置文件
                        }
                    }, id, password, verification);
                    loginDialog.show();
                }
            }
        });

        autoLogin.setChecked(autoLoginC.getBoolean("AutoLogin", true));
        autoLogin.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                editorAutoLogin.putBoolean("AutoLogin", isChecked);
                editorAutoLogin.apply();
            }
        });

        forgetPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(LoginActivity.this, "忘记密码", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        long secondTime = System.currentTimeMillis();
        if (secondTime - firstTime > 2000) {
            Snackbar.make(LoginActivity.this.findViewById(android.R.id.content), "再按一次将退出School ！", Snackbar.LENGTH_SHORT).show();
            firstTime = secondTime;
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    //初始化验证码
    /**
     * 获取验证码必须要添加上cookie   否则获取的验证码无效
     */
    private void initCode() {
        OkHttpUtils.get().url(codeUrl).addHeader("Origin", "http://61.139.105.138")
                .addHeader("Host", "61.139.105.138")
                .addHeader("Referer", "http://61.139.105.138/default2.aspx")
                .addHeader("Cookie", "ASP.NET_SessionId=w3m4lm55etch0nqdyd3l052m; safedog-flow-item=")
                .build().connTimeOut(5000).execute(new BitmapCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Toast.makeText(getApplicationContext(),"获取图片失败",Toast.LENGTH_LONG).show();
            }

            @Override
            public void onResponse(Bitmap response, int id) {
                Toast.makeText(getApplicationContext(),"获取图片成功",Toast.LENGTH_LONG).show();
                verificationImage.setImageBitmap(response);
            }
        });
    }

    //切换验证码   验证码点击刷新onclick  onclick=“reloadCode”
    public void reloadCode(View view) {
        codeUrl += '?';
        initCode();
    }


}
